<?php

/**
 * 新申友雅思接口 API
 * Created by PhpStorm.
 * User: sjeam
 */

namespace app\modules\cn\controllers;


use app\libs\IeltsController;
use app\libs\Method;
use app\libs\VerificationCode;


use app\modules\cn\models\LoginLog;
use yii;

use app\libs\ToeflApiControl;



use app\libs\Sms;

use app\modules\cn\models\SslToken;
use app\modules\cn\models\Collect;

use app\modules\cn\models\Login;


use UploadFile;


header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
class NewApiController extends IeltsController
{
    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    public $enableCsrfValidation = false;

    /**
     * 点击获取验证码
     * @sjeam
     */
    public function actionVerificationCode(){
        $_vc = new VerificationCode();  //实例化一个对象
        $_vc->doimg();
        Yii::$app->session->set('verificationCode',$_vc->getCode());//验证码保存到SESSION中
    }

    /**
     * 短信登录
     * @Obelisk
     */

    public function actionPhoneLogin()
    {
        $login = new Login();
        $phone = Yii::$app->request->post('phone');

        $code = Yii::$app->request->post('code');

        $session = Yii::$app->session;

        // $source =$session->get('source');
        $source = Yii::$app->request->post('source',10);

        $url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 
        // $source =$session->get('source',6);
        $ipInfo = Yii::$app->request->getUserIP();
        $data = Method::getIpInfo($ipInfo);
        // $country = $data[0];
        $city = $data;

        //1是官网pc 2论坛 3留学app 4小程序 5直播 6gmat 8旧雅思 9申友课程 10申友新雅思
        if ($source == 1) {
            $source = 'PC-申友官网';
        } elseif ($source == 2) {
            $source = 'BBS';
        } elseif ($source == 3) {
            $source = 'PC-申友留学';
        } elseif ($source == 5) {
            $source = '直播';
        } elseif ($source == 6) {
            $source = 'PC-申友GMAT';
        } elseif ($source == 8) {
            $source = 'PC-申友旧雅思';
        } elseif ($source == 10) {
            $source = 'PC-申友新雅思';
        }else{
            $source = 'PC-其他';
        }

        $checkTime = $login->checkTime();

        if ($checkTime) {

            $checkCode = $login->checkCode($phone, $code);

            if ($checkCode) {
                $sign = uc_get_user($phone,2);
                if($sign){
                    list($uid, $username, $email, $phone,$nickname) = $sign;
                    // $session->set('uid', $uid);
                    $res['type'] = 2;
                    if(empty($nickname)){
                        $res['check'] = 0;
                    }else{
                        $res['check'] = 1;
                    }
                }else{
                    $phonepass = 'syw'.rand(1000,9999);
                    $username = 'syw'.time();
                    // $uid = uc_user_register($username,$phonepass,'',$phone,$source,time(),$ipInfo);
                    $uid = uc_user_register($username,$phonepass,'',$phone,$source,time(),'','',$ipInfo,$city,$url);
                    $res['type'] = 1;
                    $res['check'] = 0;
                    $res['password'] = $phonepass;
                    // $session->set('uid', $uid);
                    $nickname = Method::getNickanme();
                    $status = uc_user_checknickname($nickname);
                    while ($status != 1){
                        $nickname = Method::getNickanme();
                        $status = uc_user_checknickname($nickname);
                    }
                    uc_user_nickname_edit($nickname,$uid);
                    uc_user_edit_integral3($uid,'注册成功',1,Yii::$app->params['reward']['registerReward'],$source); // todo
                }
                $type = 1;
                $time = time();
                $token = md5($uid.$time);
                $rea = SslToken::find()->where("uid=$uid and type=1")->asArray()->one();
                $ip = Yii::$app->request->getUserIP();
                if($rea){
                    SslToken::updateAll(['token' => $token,'ip' => $ip,'updateTime' => $time],"uid=$uid and type=1");
                }else{
                    $model = new SslToken();
                    $model->token = $token;
                    $model->ip = $ip;
                    $model->type = $type;
                    $model->uid = $uid;
                    $model->updateTime = $time;
                    $model->save();
                }
                // $session->set('uid',$uid);
                // if($res['check'] == 1){
                //     // var_dump(111);die;
                //     setcookie('sslToken',$token,($time+86400*60),'/','.thinkuprep.com');
                //     setcookie('sslTokenOut','out',($time-3600),'/','.thinkuprep.com');
                // }
                setcookie('sslToken',$token,($time+86400*60),'/','.thinkuprep.com');
                setcookie('sslTokenOut','out',($time-3600),'/','.thinkuprep.com');
                // Yii::$app->session->set('uid',$uid);
                Yii::$app->session->set('sslToken',$token);
                $res['code'] = 1;
                $res['url'] = $session->get('url');
                $res['message'] = '登录成功';
            } else {

                $res['code'] = 0;

                $res['message'] = '验证码错误';

                $res['type'] = '1';

            }

        } else {

            $res['code'] = 0;

            $res['message'] = '验证码过期';

            $res['type'] = '1';

        }

        die(json_encode($res));

    }
 


   
    /**
     * 短信接口
     * @sjeam
     */

    public function actionPhoneCode()

    {

        $phoneTime = Yii::$app->session->get('phoneTime');
        if(!isset($phoneTime) || time()-$phoneTime<2){
            $res['code'] = 0;
            $res['message'] = '路径错误';
            die(json_encode($res));
        }
        $session = Yii::$app->session;

        $sms = new Sms();

        $phoneNum = Yii::$app->request->post('phoneNum');
        $type = Yii::$app->request->post('type');
        $ip = Yii::$app->request->getUserIP();
        $res = Method::confirmPhone($ip,$phoneNum,'PC');
        if(!$res['sign']){
            $res['code'] = 0;
            $res['message'] = $res['content'];
            die(json_encode($res));
        }
        if($type == 1){
            $message = '注册';
        }elseif($type == 9){
            $message = '绑定';
        }elseif($type == 2){
            $message = '找回';
        }else{
            $message = '登录';
        }
        if (!empty($phoneNum)) {
            if($type == 1){
                $status = uc_user_checkphone($phoneNum);
                if($status != 1){
                    $res['code'] = 0;
                    $res['message'] = '电话已注册';
                    die(json_encode($res));
                }
            }
            $phoneCode = mt_rand(100000, 999999);

            $session->set($phoneNum . 'phoneCode', $phoneCode);

            $session->set('phoneTime', time());

            $content = '申友网验证码：' . $phoneCode . '（10分钟有效），您正在通过手机' . $message . '申友网免费会员！';
            $sms->send($phoneNum, $content, $ext = '', $stime = '', $rrid = '');

            $res['code'] = 1;

//            $res['phonecode'] = $phoneCode;

            $res['message'] = '短信发送成功！';

        } else {

            $res['code'] = 0;

            $res['message'] = '发送失败!手机号码为空！';

        }

        die(json_encode($res));

    }

    






    /**
     *登录
     */
    public function actionWebLogin()
    {
        $apps = Yii::$app->request;

        $session = Yii::$app->session;
        if ($apps->isPost) {
            $verificationCode = $apps->post('verificationCode', '');
            $userName = $apps->post('userName','');
            $userPass = $apps->post('userPass','');
            $encrypt= $apps->post('encrypt','');
            if($encrypt!=false){
                $userPass = $userPass!=false?base64_decode($userPass):'';
                $userName = base64_decode($userName);
            }//加密后的解密

            if($verificationCode=='123456'&& $userName=='18582573024'){//审核专用
            } else {
                if ($verificationCode) {
                    if (strtolower($session->get('verificationCode')) != strtolower($verificationCode)) {
                        $re['code'] = 0;
                        $re['message'] = '验证码错误';
                        die(json_encode($re));
                    }
                }
            }

            if (!$userName) {

                $re['code'] = 0;

                $re['message'] = '请输入用户名';

                die(json_encode($re));

            }
      
            list($uid,$nickname) = uc_user_ssl_login($userName, $userPass);
            if ($uid < 0) {
                list($uid,$nickname) = uc_user_ssl_login($userName, $userPass, 1);
                if ($uid < 0) {
                    list($uid,$nickname) = uc_user_ssl_login($userName, $userPass, 2);
                }
            }
       
            if ($uid > 0) {
                $type = 1;
                $time = time();
                $token = md5($uid.$time);
                $res = SslToken::find()->where("uid=$uid and type=1")->asArray()->one();
                $ip = Yii::$app->request->getUserIP();
                if($res){
                    SslToken::updateAll(['token' => $token,'ip' => $ip,'updateTime' => $time],"uid=$uid and type=1");
                }else{
                    $model = new SslToken();
                    $model->token = $token;
                    $model->ip = $ip;
                    $model->type = $type;
                    $model->uid = $uid;
                    $model->updateTime = $time;
                    $model->save();
                }
                // Yii::$app->session->set('uid',$uid);
                Yii::$app->session->set('sslToken',$token);
                if(empty($nickname)){
                    $re['check'] = 0;
                }else{
                    // setcookie('sslToken',$token,($time+86400*60),'/','.thinkuprep.com');
                    // setcookie('sslTokenOut','out',($time-3600),'/','.thinkuprep.com');
                    $re['check'] = 1;
                    $re['url'] = $session->get('url');
                }
                setcookie('sslToken',$token,($time+86400*60),'/','.thinkuprep.com');
                setcookie('sslTokenOut','out',($time-3600),'/','.thinkuprep.com');
                // Yii::$app->session->set('uid',$uid);
                Yii::$app->session->set('sslToken',$token);

                $re['code'] = 1;
                $re['sslToken'] = $token;
                $re['message'] = '登录成功';
            } else {
                $re['code'] = 0;
                $re['message'] = '用户名或密码错误';
            }
            die(json_encode($re));
        }
    }
    public function actionRegister()
    {
        $login = new Login();
        $session = Yii::$app->session;
        $registerStr = Yii::$app->request->post('registerStr');
        if(!$registerStr){
            die(json_encode(['code' => 0,'message' => '请填写邮箱或者电话']));
        }
        $pass = Yii::$app->request->post('pass');

        $code = Yii::$app->request->post('code');

        $type = Yii::$app->request->post('type');

        // $source =$session->get('source');
        $source = Yii::$app->request->get('source',10);
        $ip = Yii::$app->request->getUserIP();
        $ipInfo = Method::getIpInfo($ip);
        //1是官网pc 2论坛 3留学app 4小程序 5直播 6gmat 8旧雅思 9申友课程 10申友新雅思
        if ($source == 1) {
            $source = 'PC-申友官网';
        } elseif ($source == 2) {
            $source = 'BBS';
        } elseif ($source == 3) {
            $source = 'PC-申友留学';
        } elseif ($source == 5) {
            $source = '直播';
        } elseif ($source == 6) {
            $source = 'PC-申友GMAT';
        } elseif ($source == 8) {
            $source = 'PC-申友旧雅思';
        } elseif ($source == 10) {
            $source = 'PC-申友新雅思';
        }else{
            $source = 'PC-其他';
        }

//        var_dump($ipInfo);die;

        $userName = Yii::$app->request->post('userName','');
        $url = Yii::$app->request->post('url');
        if(!$userName){
            $userName =  'lgw'.time();
        }


        $checkTime = $login->checkTime();

        if ($checkTime) {

            $checkCode = $login->checkCode($registerStr, $code);

            if ($checkCode) {
                $domain = strpos($registerStr, '@');
                if ($domain === false) {//手机号注册
                    $uid = uc_user_register($userName,md5($pass),'',$registerStr,$source,time(),'','',$ip,$ipInfo,$url);
                } else {//邮箱注册
                    $uid = uc_user_register($userName,md5($pass),$registerStr,'',$source,time(),'','',$ip,$ipInfo,$url);
                }
                if($uid <0){
                    if($uid == -1) {
                        $res['code'] = 0;
                        $res['message'] = '用户名已经被注册';
                    } elseif($uid == -2) {
                        $res['code'] = 0;
                        $res['message'] = '包含要允许注册的词语';
                    } elseif($uid == -3) {
                        $res['code'] = 0;
                        $res['message'] = '用户名已经存在';
                    } elseif($uid == -4) {
                        $res['code'] = 0;
                        $res['message'] = 'Email 格式有误';
                    } elseif($uid == -5) {
                        $res['code'] = 0;
                        $res['message'] = 'Email 不允许注册';
                    } elseif($uid == -6) {
                        $res['code'] = 0;
                        $res['message'] = '该 Email 已经被注册';
                    } elseif($uid == -7){
                        $res['code'] = 0;
                        $res['message'] = '电话已被注册';
                    }elseif($uid == -8){
                        $res['code'] = 0;
                        $res['message'] = '昵称已被注册';
                    }
                }else{
      
                    $nickname = Method::getNickanme();
                    $status = uc_user_checknickname($nickname);
                    while ($status != 1){
                        $nickname = Method::getNickanme();
                        $status = uc_user_checknickname($nickname);
                    }
                    uc_user_nickname_edit($nickname,$uid);
                    uc_user_edit_integral3($uid,'注册成功',1,Yii::$app->params['reward']['registerReward'],$source);  // todo
                    // Yii::$app->session->set('uid',$uid);
                    $type = 1;
                    $time = time();
                    $token = md5($uid.$time);
                    $udata = SslToken::find()->where("uid=$uid and type=1")->asArray()->one();
                    $ip = Yii::$app->request->getUserIP();
                    if($udata){
                        SslToken::updateAll(['token' => $token,'ip' => $ip,'updateTime' => $time],"uid=$uid and type=1");
                    }else{
                        $model = new SslToken();
                        $model->token = $token;
                        $model->ip = $ip;
                        $model->type = $type;
                        $model->uid = $uid;
                        $model->updateTime = $time;
                        $model->save();
                    }
                    setcookie('sslToken',$token,($time+86400*60),'/','.thinkuprep.com');
                    setcookie('sslTokenOut','out',($time-3600),'/','.thinkuprep.com');
                    // Yii::$app->session->set('uid',$uid);
                    Yii::$app->session->set('sslToken',$token);
                    $res['code'] = 1;
                    $res['message'] = '注册成功';
                }
            } else {

                $res['code'] = 0;

                $res['message'] = '验证码错误';

                $res['type'] = '1';

            }

        } else {

            $res['code'] = 0;

            $res['message'] = '验证码过期';

            $res['type'] = '1';

        }

        die(json_encode($res));

    }

     /**
     * 发送邮箱
     * @sjeam
     */

    public function actionSendMail()
    {

        $session = Yii::$app->session;

        $emailCode = mt_rand(100000, 999999);

        $email = Yii::$app->request->post('email');
        $type = Yii::$app->request->post('type');
        if($type == 1){
            $status = uc_user_checkemail($email);
            if($status != 1){
                $res['code'] = 0;
                $res['message'] = '邮箱已注册！';
                die(json_encode($res));
            }
            $message = '注册';
        }elseif($type == 2){
            $status = uc_user_checkemail($email);
            if($status != 1){
                $res['code'] = 0;
                $res['message'] = '邮箱已注册！';
                die(json_encode($res));
            }
            $message = '修改';
        }elseif($type == 9){
            $message = '绑定';
        }else{
            $message = '找回';
        }
        $session->set($email . 'phoneCode', $emailCode);

        $session->set('phoneTime', time());

        $mail = Yii::$app->mailer->compose();

        $mail->setTo($email);

        $mail->setSubject("【申友网】邮件验证码");

        $mail->setHtmlBody('

            <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

            <div style="width: 800px;margin: 0 auto;margin-bottom: 10px">

                 <img src="http://www.thinkuprep.com/cn/images/indexNew/icon-logo.png" alt="logo">

            </div>

            <div style="width: 830px;border: 1px #dcdcdc solid;margin: 0 auto;overflow: hidden">

                 <p style="font-weight: bold;font-size: 18px;margin-left: 20px;color: #34388e;font-family: 微软雅黑;">亲爱的用户 ：</p>

                <span style="margin-left: 20px;font-family: 微软雅黑;">

            你好！你正在'.$message.'申友网(<a href="http://www.thinkuprep.com">www.thinkuprep.com</a>)账户。你的验证码为：【<span style="color:#ff913e;">' . $emailCode . '</span>】。（有效期为：此邮件发出后48小时）
                </span>
                                <p style="margin-left: 20px;font-family: 微软雅黑;">
                            <span style="font-weight:bold">注：</span>有问题请咨询题库管理员QQ/微信：2095453331
                </p>
            <div style="width: 100%;background: #e8e8e8;padding:5px 20px;font-size:12px;box-sizing: border-box;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;margin-top: 30px;color: #808080;font-family: 微软雅黑;">

            温馨提示：请你注意保护你的邮箱，避免邮件被他人盗用哟！

            </div>

            </div>

            <div style="font-size: 12px;width: 800px;margin: 0 auto;text-align: right;color: #808080;">


        </div>

        '

        );    //发布可以带html标签的文本

        if ($mail->send()) {

            $res['code'] = 1;

            $res['message'] = '邮件发送成功！';

//            $res['emailCode'] = $emailCode;

        } else {

            $res['code'] = 0;

            $res['message'] = '邮件发送失败！';

        }

        die(json_encode($res));

    }
    /**
     * 修改昵称
     * @Obelisk
     * /cn/ssl-api/change-nickname
     */
    public function actionChangeNickname(){
        $time = time();
        $session = Yii::$app->session;
        $uid = $session->get('uid');
        $nickname = Yii::$app->request->post('nickname');
        if(!$nickname){
            $res['code'] = 0;
            $res['message'] = '请输入您的昵称';
            die(json_encode($res));
        }
        $status = uc_user_checknickname($nickname);
        if($status != 1){
            $res['code'] = 0;
            $res['message'] = '该昵称已被占用';
            die(json_encode($res));
        }
        uc_user_nickname_edit($nickname,$uid);
        $token = Yii::$app->session->get('sslToken');
        setcookie('sslToken',$token,($time+86400*60),'/','.thinkuprep.com');
        setcookie('sslTokenOut','out',($time-3600),'/','.thinkuprep.com');
        $res['code'] = 1;
        $res['message'] = '设置成功';
        $res['url'] = $session->get('url');
        die(json_encode($res));

    }
    /**
     * 网页登出
     */
    public function actionLoginOut(){
        $request_url = @apache_request_headers()['Origin'];  //TODO Apache 服务方式
        header('Access-Control-Allow-Origin: '.$request_url.'');
        header('Access-Control-Allow-Credentials:true');
        header('Access-Control-Allow-Headers: X-Requested-With');
        header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
        $time = time();
        setcookie('sslTokenOut','out',($time+86400*60),'/','.thinkuprep.com');
        setcookie('sslToken','out',($time-3600),'/','.thinkuprep.com');
        $re = [
            'code' => 1,
            'message' => '登出成功'
        ];
        session_destroy();
        die(json_encode($re));
    }



        /**
     * 修改登录密码 --- 找回密码
     * @sjeam  
     * 接口：  /cn/api/change-password         post ：passowrd   phone
     */
    public function actionChangePassword(){
        $login = new Login();
        $session = Yii::$app->session;
        // $uid = $session->get('uid');
        $passowrd = Yii::$app->request->post('passowrd');
        $phone = Yii::$app->request->post('phone');
        $phonecode =Yii::$app->request->post('phonecode');
        if(!$passowrd){
            $res['code'] = 0;
            $res['message'] = '请输入新密码';
            die(json_encode($res));
        }
        $status  =  uc_user_checkphone($phone);
        // 手机号不存在， 就 是未注册
        if($status == 1){
            $res['code'] = 0;
            $res['message'] = '手机号码未注册';
            die(json_encode($res));
        }
       $usercode = $session->get($phone.'phoneCode');
       $checkTime = $login->checkTime();
        if (!$checkTime) {
            $res['code'] = 0;
            $res['message'] = '验证码已过期';
            die(json_encode($res));
        }
        if($phonecode!=$usercode){
            $res['code'] = 0;
            $res['message'] = '验证码错误';
            die(json_encode($res));
        }
        uc_user_phone_edit($phone,$passowrd);
        // $success_content =  uc_user_synlogin($uid);
        // $session->set('success_content',$success_content);
        // $res['success_content'] = $success_content;
        $res['code'] = 1;
        $res['message'] = '设置成功';
        $res['url'] = $session->get('url');
        die(json_encode($res));

    }
}